<template>
  <div class="dashboard-container">

    <div class="left">
      <el-tree :data="list" :props="defaultProps" heighlight-current default-expand-all @node-click="handleNodeClick"
        ref="tree"></el-tree>
    </div>

    <div class="right">
      <div class="opt">
        <el-button type="primary" size="mini" @click="handleSave">保存</el-button>
        <el-button type="primary" size="mini" @click="handleAdd(1)">新增一级公司</el-button>
        <el-button type="primary" size="mini" @click="handleAdd(2)">新增下级公司</el-button>
        <el-button type="danger" size="mini" @click="handleDelete">删除机构</el-button>
      </div>
      <div class="content">
        <div>
          <el-form :rules="rules" ref="form" :model="temp" size="mini" label-width="120px" >
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="公司名:" prop="name">
                  <el-input placeholder="请输入" v-model="temp.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="省份:" prop="provinceId">
                  <el-select filterable clearable v-model="temp.provinceId" placeholder="请选择" style="width: 100%;"
                    @change="(val)=>handleChangeProvince(val,2)">
                    <el-option v-for="item, index in provinceList" :key="index" :label="item.name"
                      :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="城市:" prop="cityId">
                  <el-select filterable clearable v-model="temp.cityId" placeholder="请选择" style="width: 100%;"
                    @change="(val)=>changeCity(val, 2)">
                    <el-option v-for="item, index in cityList" :key="index" :label="item.name"
                      :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="区县:" prop="areaId">
                  <el-select filterable clearable v-model="temp.areaId" placeholder="请选择" style="width: 100%;">
                    <el-option v-for="item, index in areaList" :key="index" :label="item.name"
                      :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="企业类型:" prop="companyTypeEiid">
                  <el-select filterable clearable v-model="temp.companyTypeEiid" placeholder="请选择" style="width: 100%;">
                    <el-option v-for="item in patternList" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="详细地址:" prop="detailAddress">
                  <el-input type="textarea" :rows="2" placeholder="请输入" v-model="temp.detailAddress"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="业务类型:">
                  <el-select 
                      filterable 
                      clearable
                      v-model="temp.customerCompanyBusinessEiids" 
                      placeholder="请选择" 
                      style="width: 100%;"
                      multiple
                    >
                      <el-option 
                        v-for="item,index in ustomerCompanyBusinessEiidList" 
                        :key="index" 
                        :label="item.label" 
                        :value="item.value"
                      ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="业务员:">
                  <span v-if="temp.businessUser" style="margin-right: 10px;">{{ temp.businessUser.realName }}</span>
                  <el-button type="text" @click="selectUser('buss')">选择</el-button>
                  <el-button type="text" @click="deleteUser('buss')" style="color: red;">删除</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="负责人:">
                  <span v-if="temp.leader" style="margin-right: 10px;">{{ temp.leader.realName }}</span>
                  <el-button type="text"  @click="selectUser('leader')">选择</el-button>
                  <el-button type="text" @click="deleteUser('leader')" style="color: red;">删除</el-button>
                </el-form-item>
              </el-col>
              
              
              
            </el-row>
            <el-row>
                <el-col :span="8">
                  <el-form-item label="询价回价人员:">
                    <span  style="margin-right: 10px;">
                      <span v-for="user in temp.inquiryUser">{{ user.realName }};</span>
                    </span>
                    <el-button type="text" @click="selectUser('inquiry')">管理</el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="询价分配策略:" prop="inquiryAssignPolicy">
                    <el-select filterable clearable v-model="temp.inquiryAssignPolicy" placeholder="请选择" style="width: 100%;">
                      <el-option v-for="item in POLICY_LIST" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                    </el-select>
                  </el-form-item> 
                </el-col>
              </el-row>
          </el-form>

          <h3>已有权限： <el-button type="primary" size="mini" @click="handleAuth">新增</el-button></h3>
          <el-table :data="auth">
            <el-table-column label="市" prop="cityName"></el-table-column>
            <el-table-column label="区" prop="areaName"></el-table-column>
            <el-table-column label="资产类型" prop="propertyTypesName"></el-table-column>
            <el-table-column label="对象类型" prop="objectTypeName"></el-table-column>
            
            <el-table-column label="操作">
              <template slot-scope="{row, $index}">
                <el-button type="text" style="color: red;" @click="handleDeleteAuth($index, row.objectType)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 新增权限 -->
    <el-dialog :visible.sync="dialogVisibleAuth" :close-on-click-modal="false" @close="dialogVisibleAuth = false"
      title="新增权限" width="500px">
      <el-form :model="tempAuth" size="mini" label-width="80px" label-position="left">
        <el-form-item label="城市">
          <el-select filterable clearable v-model="tempAuth.cityId" placeholder="请选择" style="width: 100%;"
            @change="changeCity2">
            <el-option v-for="item, index in authCityList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区">
          <el-select filterable clearable v-model="tempAuth.areaId" placeholder="请选择" style="width: 100%;"
            @change="changeArea">
            <el-option v-for="item, index in authAreaList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="对象类型">
          <el-select v-model="tempAuth.objectType" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item, index in OBJECT_TYPE_LIST_ROLE" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资产类型" v-if="tempAuth.objectType==3">
          <el-select multiple clearable v-model="tempAuth.propertyTypes" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item, index in TARGET_TYPE_LIST" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleEnsureAuth">确认</el-button>
          <el-button @click="dialogVisibleAuth = false">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 新增公司 -->
    <el-dialog title="新增公司" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form label-width="100px" label-position="left" ref="form" :rules="rules" :model="tempAdd">
        <el-form-item label="上级公司:" v-if="tempAdd.parentId">
          {{tempAdd.parentName}}
        </el-form-item>
        <el-form-item label="公司名:" prop="name">
          <el-input placeholder="请输入" v-model="tempAdd.name"></el-input>
        </el-form-item>
        <el-form-item label="省份:" prop="provinceId">
          <el-select filterable clearable v-model="tempAdd.provinceId" placeholder="请选择" style="width: 100%;"
            @change="handleChangeProvince">
            <el-option v-for="item, index in provinceList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:" prop="cityId">
          <el-select filterable clearable v-model="tempAdd.cityId" placeholder="请选择" style="width: 100%;"
            @change="changeCity">
            <el-option v-for="item, index in cityList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区县:" prop="areaId">
          <el-select filterable clearable v-model="tempAdd.areaId" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item, index in areaList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业类型:" prop="companyTypeEiid">
          <el-select filterable clearable v-model="tempAdd.companyTypeEiid" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in patternList" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址:" prop="detailAddress">
          <el-input type="textarea" :rows="2" placeholder="请输入" v-model="tempAdd.detailAddress"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit('form')">保存</el-button>
          <el-button @click="dialogVisible=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 选择业务员 -->
    <el-dialog 
      title="选择"
      :visible.sync="dialogVisibleUser" 
      :close-on-click-modal="false"
      width="600px"
    > 
      <div v-if="selectType=='inquiry'">
        已选择人员：
        <el-tag
          v-for="tag,index in temp.inquiryUser"
          :key="tag.name"
          closable
          @close="handleClose(tag, index)"
          style="margin-right: 5px;"
        >
          {{tag.realName}}
        </el-tag>
      </div>
      <el-table :data="userList">
        <el-table-column prop="realName" label="真实姓名"></el-table-column>
        <el-table-column prop="department.name" label="部门"></el-table-column>
        <el-table-column prop="phone" label="手机"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{row}">
            <el-button type="text" @click="submitSelectUser(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageIndex+1"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="params.pageCount"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
      <el-button type="primary" @click="dialogVisibleUser=false">确定</el-button>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { companyCreate, companyUpdate, companyDelete, companyGetTree, companyInfo } from '@/api/company'
import { TARGET_TYPE_LIST, OBJECT_TYPE_LIST_ROLE, POLICY_LIST } from '@/utils/common'
import { commonGetProvinceList, commonGetAreaList } from '@/api/common'
import { geoAuthGetCollection, geoAuthUpdate } from '@/api/geoAuth'
import { enumInfo } from '@/api/enum'
import { getInfo } from '@/api/user'
import moment from 'moment'
import { transfromData } from '@/utils/tools'
import { userGetList } from '@/api/user'  

export default {
  name: 'Staffcompany',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data() {
    return {
      TARGET_TYPE_LIST,
      OBJECT_TYPE_LIST_ROLE,
      POLICY_LIST,
      rules: {
        name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        provinceId:[{ required: true, message: '请选择省份', trigger: 'blur' }],
        cityId:[{ required: true, message: '请选择城市', trigger: 'blur' }],
        companyTypeEiid: [{ required: true, message: '请选择公司类型', trigger: 'blur' }],
      },
      params: {
        parentId: 0,
        pageCount: 999,
        pageIndex: 0,
        userType: 2,
        name: '',
      },
      total: 0,
      list: [],
      dialogVisible: false,
      dialogType: 'create',
      temp: {
        name: '',
        provinceId: '',
        userType: 2,
        cityId: '',
        name: '',
        patternId: '', // 公司模型
        parentId: '', //上级公司id
        detailAddress: '',
        leaderUserId: '', //负责人
        businessUserId: '', //业务员
        customerCompanyBusinessEiids:[], //客户公司业务列表
        inquiryAssignPolicy: '', //分配策略
        inquiryUserIds: [], // 回价人员列表
        inquiryUser: [], //带用户信息的
      },
      loading: false,
      defaultProps: {
        children: 'companies',
        label: 'name'
      },
      provinceList: [], //省份列表
      cityList: [], //城市列表
      patternList: [], //企业类型列表
      areaList: [],
      auth: [],
      dialogVisibleAuth: false,
      tempAuth: {
        cityId: '',
        areaId: '',
        propertyTypes: [],
        objectType: 3
      },
      authCityList: [],
      authAreaList: [],
      tempAdd: {},
      paramsUser: {
        pageIndex: 0,
        pageCount: 10,
        type: '', //1员工  2客户
      },
      userList: [],
      total: 0,
      dialogVisibleUser: false,
      selectType: '',
      ustomerCompanyBusinessEiidList: []
    }

  },
  async mounted() {
    //获取业务列表
    let yewuType = await enumInfo({ id: 36 })
    this.ustomerCompanyBusinessEiidList = yewuType.items.filter(item=>item.selectFlag==1).map(item=>{
        let name = item.name;
        let nowItem = JSON.parse(JSON.stringify(item));
        for(let i=1;i<item.level;i++){
          let parent =  yewuType.items.filter(aItem=>aItem.id==nowItem.parentId);
          if(parent.length>0){
            name = parent[0].name + '-' + name
          }
          nowItem = parent;
        }
        return { label: name, value: item.id }
    })
    this.getProvince();
    this.getPattern();
  },

  methods: {
    //删除该询价人员
    handleClose(row, index){
      //删除掉对应的对象
      this.temp.inquiryUserIds.splice(index, 1)
      this.temp.inquiryUser.splice(index, 1)
    },
    deleteUser(type){
      if(type=='buss'){
        this.temp.businessUserId = ''
        this.temp.businessUser = '';
      }
      if(type=='leader'){
        this.temp.leaderUserId = ''
        this.temp.leader = ''
      }
    },
    // 提交选择
    submitSelectUser(row){
      if(this.selectType=='inquiry'){
        //判断是否在已选择的id里面，如果是则不做处理
        if(this.temp.inquiryUser.filter(item=>item.id==row.id).length>=1)return;
        //如果是回价，那就是多选，选择一个也不会结束
        this.temp.inquiryUser.push(row)
        return;
      }
      if(this.selectType=='buss'){
        this.temp.businessUserId = row.id
        this.temp.businessUser = row;
      }
      if(this.selectType=='leader'){
        this.temp.leaderUserId = row.id
        this.temp.leader  = row
      }
      this.dialogVisibleUser = false;
    },
    //点击选择
    selectUser(type){
      this.selectType = type
      //buss 业务员  leader 领导
      if(type=='buss'){
        this.paramsUser = {
          pageIndex: 0,
          pageCount: 10,
          type: 1, //1员工  2客户
        }
      }
      if(type=='leader'){
        this.paramsUser = {
          pageIndex: 0,
          pageCount: 10,
          type: 2, //1员工  2客户
          companyId: this.temp.id
        }
      }
      if(type=='inquiry'){
        //回价人员是多选
        this.paramsUser = {
          pageIndex: 0,
          pageCount: 10,
          type: 1, //1员工  2客户
        }
      }
      this.dialogVisibleUser = true;
      this.getUserList();
    },
    // 修改每页数量
    handleSizeChange(val){
      this.params.pageIndex = 0;
      this.params.pageCount = val;
      this.getData();
    },
    // 切换分页
    handleCurrentChange(val){
      this.params.pageIndex = val - 1;
      this.getData();
    },
    //获取用户列表
    async getUserList(){
      let data = await userGetList(this.paramsUser);
      this.userList = data.list;
      this.total = data.totalCount;
    },
    //请求接口
    async updateAuth(auth, objectType) {
      let geoAuths = auth.length > 0 ? `[${auth.filter(item=>item.objectType==objectType).map(item => JSON.stringify(item)).join(',')}]` : '[]';
      await geoAuthUpdate({ companyId: this.temp.id, geoAuths, objectType })
      this.$message.success({ message: '保存成功' })
      this.getCollection();
    },
    //删除元素
    handleDeleteAuth(index, objectType) {
      this.auth.splice(index, 1);
      this.updateAuth(this.auth, objectType);
    },
    //保存权限的新增
    async handleEnsureAuth() {
      this.dialogVisibleAuth = false;
      let { cityId, areaId, propertyTypes, objectType } = this.tempAuth;
      let params = {
        cityId: cityId ? cityId : 0,
        areaId: areaId ? areaId : 0,
        objectType,
        propertyTypes: propertyTypes.length > 0 ? propertyTypes.join(',') : ''
      };
     
      let auth = JSON.parse(JSON.stringify(this.auth));
      auth.push(params)
      this.updateAuth(auth, objectType);

    },
    // 保存公司
    async handleSave() {
      let temp = JSON.parse(JSON.stringify(this.temp));
      temp.inquiryUserIds = temp.inquiryUser.map(item=>item.id)
      await companyUpdate(temp)
      this.$message.success({ message: '保存成功' })
      this.setTempData({id: this.temp.id});
    },
    // 点击新增权限
    handleAuth() {
      this.dialogVisibleAuth = true;
      this.tempAuth = {
        cityId: '',
        areaId: '',
        propertyTypes: [],
        tempAuth: 3,
        objectType: 3
      }
    },
    // 点击删除
    handleDelete() {
      this.$confirm('此操作将永久删除该公司, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await companyDelete({ id: this.temp.id })
        this.getData();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 获取企业类型
    async getPattern() {
      let data = await enumInfo({ id: 24 })
      this.patternList = data.items.map(item => {
        return { label: item.name, value: item.id }
      })
    },
    //修改区域
    changeArea() {

    },
    //修改城市
    async changeCity2(val) {
      // 请求区县信息
      let data = await commonGetAreaList({ geoLevel: 4, cityId: val })
      this.authAreaList = data;

      //清空之前的区县选择
      this.tempAuth.areaId = '';
    },
    //修改城市
    async changeCity(val, type) {
      // 请求区县信息
      let data = await commonGetAreaList({ geoLevel: 4, cityId: val })
      this.areaList = data;

      if(type==2){
        //清空之前的区县选择
        this.temp.areaId = '';
      }
      
    },
    // 修改省份，同步更新城市列表
    handleChangeProvince(val, type) {
      if (val) {
        this.cityList = this.provinceList.filter(item => item.id == val)[0].citys;
      } else {
        this.cityList = [];
      }
      if(type==2){
        this.temp.cityId = '';
        this.temp.areaId = '';
      }
      
    },
    //获取省份列表
    async getProvince() {
      let data = await commonGetProvinceList({ geoLevel: 2 });
      this.provinceList = data;
      this.authCityList = data.filter(item => item.id == 11)[0].citys
      this.getData();
    },
    // 设置当前的公司内容
    async setTempData(node) {
      let data = await companyInfo({ id: node.id })
      data.customerCompanyBusinessEiids = data.customerCompanyBusinessEiids.split(',').map(item=>Number(item))
      if(data.inquiryUserIds){
        //如果有回价人员，就查询所有回价人员信息
        let UserList = data.inquiryUserIds.split(',')
        let inquiryUser = [];
        for(let i=0;i<UserList.length;i++){
          let user = await getInfo({ id: UserList[i] });
          inquiryUser.push(user)
        }
        data.inquiryUser = inquiryUser;
        data.inquiryUserIds = UserList
      }else{
        data.inquiryUserIds = []
        data.inquiryUser = []
      }
      if(data.inquiryAssignPolicy==0){
        data.inquiryAssignPolicy = ""
      }
      this.temp = data;
      console.log(this.temp)
      if(this.temp.areaId==0){
        this.temp.areaId=""
      }
      // 获取市、街道数据
      if (data.provinceId > 0) {
        this.handleChangeProvince(data.provinceId);
        if (data.cityId > 0) {
          this.changeCity(data.cityId);
        }
      }
      this.getCollection();
    },
    // 获取当前公司的权限
    async getCollection() {
      let data = await geoAuthGetCollection({ companyId: this.temp.id, objectType: 3 })
      let wData = await geoAuthGetCollection({ companyId: this.temp.id, objectType: 12 })
      data = data.concat(wData);
      // 获取的权限数据做一下解析
      data = data.map(item => {
        item.objectTypeName = transfromData(this.OBJECT_TYPE_LIST_ROLE, item.objectType)
        if (item.cityId == 0) {
          item.cityName = '全部'
        } else {
          item.cityName = item.city.name
        }

        if (item.areaId == 0) {
          item.areaName = '全部'
        } else {
          item.areaName = item.area.name
        }

        if (!item.propertyTypes) {
          item.propertyTypesName = '全部'
        } else {
          item.propertyTypesName = item.propertyTypes.split(',').map(item => {
            return transfromData(TARGET_TYPE_LIST, item)
          }).join(',')
        }
        return item;
      })
      
      this.auth = data;
    },
    //点击节点
    async handleNodeClick(node) {
      //设置当前数据
      this.setTempData(node)
    },
    //点击添加子公司
    handleAddSon(id) {
      this.$router.history.push({ path: '/custom/companyAdd?parentId=' + id })
    },
    //提交表单
    submit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await companyCreate(this.tempAdd)
          this.$message.success('创建成功')
          this.dialogVisible = false;
          this.getData();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 点击新增、编辑
    handleAdd(type) {
      this.tempAdd = {
        name: '',
        provinceId: '',
        userType: 2,
        cityId: '',
        name: '',
        patternId: '', // 公司模型
        parentId: '', //上级公司id
        detailAddress: ''
      }
      if (type == 1) {
        //一级公司
      } else {
        //二级公司
        this.tempAdd.parentId = this.temp.id
        this.tempAdd.parentName = this.temp.name
      }

      this.dialogVisible = true
    },
    //加载列表数据
    async getData() {
      this.loading = true
      let data = await companyGetTree({ userType: 2 })
      this.loading = false;
      this.list = data.map(item => {
        item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
        return item;
      });
      this.setTempData(this.list[0])
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {

    // display: flex;
    .left {
      width: 200px;
      height: 90vh;
      border: 1px solid #eee;
      padding-top: 20px;
      float: left;
      overflow-x: auto;
      overflow-y: auto;
    }

    .right {
      // flex-grow: 1; /* 右侧自适应 */
      margin-left: 200px;
      padding: 20px;
      overflow: hidden;

      .opt {
        margin-bottom: 10px;
      }
    }
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>